package vn.co.thn.web.hotvideo.common;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.datastore.Text;

public class BeanBase {
	@SuppressWarnings("unchecked")
	public static <T> T RequestToObject(HttpServletRequest request, Class<T> clazz) {
		try {
			Object object = clazz.getConstructor().newInstance();
			List<Field> fields = new ArrayList<Field>();
			fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
			Enumeration<?> e = request.getParameterNames();
			while (e.hasMoreElements()) {
				String ParameterNames = "";
				ParameterNames = (String) e.nextElement();
				for (Field field : fields) {
					field.setAccessible(true);

					if (field.getName().equalsIgnoreCase(ParameterNames)) {
						if (field.getType().isAssignableFrom(Text.class)) {
							field.set(object, new Text(request.getParameter(ParameterNames)));
						} else {
							if (field.getType().isAssignableFrom(Long.class)) {
								field.set(object,new Long(request.getParameter(ParameterNames)));
							}else{
								field.set(object, field.getType().cast(request.getParameter(ParameterNames)));
							}
														
						}

					}
				}
			}

			return (T) object;
		} catch (Exception e) {
			return null;
		}
	}
}
